package org.jeecg.modules.feeSteam.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.chargeSteam.service.IChargeSteamService;
import org.jeecg.modules.consumptionSteam.service.IConsumptionSteamService;
import org.jeecg.modules.feeSteam.entity.FeeSteam;
import org.jeecg.modules.feeSteam.service.IFeeSteamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Configuration
@EnableScheduling
@Slf4j
public class FeeSteamScheduled {

    private final IFeeSteamService feeSteamService;
    private final IConsumptionSteamService consumptionSteamService;
    private final IChargeSteamService chargeSteamService;

    @Autowired
    public FeeSteamScheduled(IFeeSteamService feeSteamService, IConsumptionSteamService consumptionSteamService, IChargeSteamService chargeSteamService) {
        this.feeSteamService = feeSteamService;
        this.consumptionSteamService = consumptionSteamService;
        this.chargeSteamService = chargeSteamService;
    }

    @Scheduled(cron = "0 0 23 * * ?")//每天23点执行一次
    public void configureTasks() throws Exception{
        log.info("执行静态定时任务时间: {}" , LocalDateTime.now());
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String today = dateFormat.format(calendar.getTime());

        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.valueOf((calendar.get(Calendar.MONTH) + 1));
        String day = String.valueOf(calendar.get(Calendar.DATE));
        Integer date = Integer.valueOf(today);

        Map<String, Object> waterProgramme = chargeSteamService.getProgramme();
        BigDecimal price = (BigDecimal) waterProgramme.get("price");
        List<Map<String, Object>> todayConsumptions = consumptionSteamService.getDayConsumption(year, month, day);
        List<FeeSteam> list = new LinkedList<>();
        for (Map<String, Object> todayConsumption : todayConsumptions){
            String dept = (String) todayConsumption.get("dept");
            BigDecimal consumption = new BigDecimal(String.valueOf(todayConsumption.get("consumption")));
            BigDecimal result = price.multiply(consumption).setScale(2, RoundingMode.HALF_UP);
            FeeSteam feeSteam = new FeeSteam();
            feeSteam.setFee(result).setDept(dept).setYear(year).setMonth(month).setDay(day).setDate(date);
            list.add(feeSteam);
        }
        log.info("即将插入的【蒸汽费】数据: {}" , list);
        feeSteamService.saveBatch(list);
    }

}
